import React, { useEffect, useState } from 'react';
import { Box, CartMiniSummary, makeToast, ThemeColorType, useViewport } from '@nova-hf/ui';
import StepWrapper from 'beta/containers/layout/StepWrapper';
import Authentication from 'beta/store/authentication';
import { IContext } from 'beta/typings/context';
import { serviceColorMap } from 'beta/utils/helpers';
import { useTranslation } from 'beta/utils/i18n';
import { inject, observer } from 'mobx-react';
import { useGetServiceTypeQuery } from 'typings/graphql';

import { CardItem } from '../components/SellingCardItem';
import { ConfirmInternetAndAbroad, InternetAndAbroadOverview } from '../containers';
import { ChangePlan } from '../containers/ConfirmInternetAndAbroad';
import { useFetchApplicableVariants, useFetchOptions } from '../hooks';

type SkrefProps = {
  customerId: string;
  serviceId: string;
  authentication: Authentication;
};

const Thjonustubreyting = ({ customerId, serviceId, authentication }: SkrefProps) => {
  const { t } = useTranslation('thjonustubreyting');
  const { isSmall } = useViewport();
  const isStaff = authentication?.isStaff;
  const [selectedVariant, setSelectedVariant] = useState<CardItem>();
  const [selectedOption, setSelectedOption] = useState<CardItem>();
  const { data } = useGetServiceTypeQuery({
    variables: {
      serviceId,
    },
  });

  const hookParams = { customerId, serviceId, isStaff };

  const { applicableVariantsAsCardItems, currentContractAsCardItem, loading, error } =
    useFetchApplicableVariants(hookParams);

  const { optionsAsCardItems } = useFetchOptions({ customerId, serviceId });

  const type = data?.service?.type;

  const options =
    type === 'Mobile'
      ? optionsAsCardItems?.filter((option) => option?.isCurrent === false)
      : undefined;
  const COLOR: ThemeColorType = serviceColorMap(type);

  const handleSelectVariant = (variant: CardItem) => {
    if (selectedVariant?.id === variant.id) {
      setSelectedVariant(undefined);
    } else {
      setSelectedVariant(variant);
    }
  };

  const handleSelectOption = (variant: CardItem) => {
    if (selectedOption?.id === variant.id) {
      setSelectedOption(undefined);
    } else setSelectedOption(variant);
  };

  useEffect(() => {
    if (error) makeToast.danger(t('toast.contractsError'), error ?? '');
  }, [error]);

  if (error) return <Box>Something went wrong...</Box>;
  if (loading) return <Box>Loading....</Box>;

  return (
    <>
      <StepWrapper
        color={COLOR}
        returnUrl={`/beta/${customerId}/thjonustur/${serviceId}`}
        title={t('title')}
        icon="mobileReturn"
        childrenBottom={
          !isSmall && (
            <Box display="flex" flexDirection="column" gap={3}>
              {(selectedVariant?.id || selectedOption?.id) && (
                <CartMiniSummary
                  cartPayNowItems={[
                    ...(selectedVariant?.id
                      ? [
                          {
                            price: selectedVariant?.price ?? 0,
                            title: selectedVariant?.title ?? '',
                          },
                        ]
                      : []),
                    ...(selectedOption?.id
                      ? [
                          {
                            price: selectedOption?.price ?? 0,
                            title: selectedOption?.title ?? '',
                          },
                        ]
                      : []),
                  ]}
                  {...((selectedOption?.id || selectedVariant?.id) && {
                    payNow: {
                      price: (selectedOption?.price ?? 0) + (selectedVariant?.price ?? 0),
                      title: t('cartMiniSummary.recurringTitle'),
                    },
                  })}
                  cartTitle={t('cartMiniSummary.title')}
                  color={COLOR}
                />
              )}
            </Box>
          )
        }
      >
        <InternetAndAbroadOverview
          optionsAsCardItems={options}
          applicableVariantsAsCardItems={applicableVariantsAsCardItems}
          onSelectVariant={handleSelectVariant}
          onSelectOption={handleSelectOption}
          selectedVariant={selectedVariant}
          selectedOption={selectedOption}
          isLoading={loading}
          color={COLOR}
        />
        <ConfirmInternetAndAbroad
          changePlan={ChangePlan.Variant}
          currentContract={currentContractAsCardItem}
          applicableVariantsAsCardItem={selectedVariant}
          optionsAsCardItem={selectedOption}
          color={COLOR}
          jumping={false}
        />
      </StepWrapper>
    </>
  );
};

Thjonustubreyting.getInitialProps = ({ pathname, query }: IContext) => {
  return {
    pathname,
    customerId: query.customerId,
    serviceId: query.serviceId,
    namespacesRequired: ['thjonustubreyting', 'skref'],
  };
};

export default inject('steps', 'authentication')(observer(Thjonustubreyting));
